#include <malloc.h>
#include <stdio.h>
#include "../heads/ArrayList.h"

ArrayList createArrayList(int initialCapacity){
    ArrayList list;
    list.array = (int *)malloc(initialCapacity * sizeof(int));
    // 数组的本质是连续空间的首地址指针
    if (list.array == NULL){
        fprintf(stderr, "顺序表初始化失败：无法为顺序表分配内存！\n");
        exit(EXIT_FAILURE);
    }
    list.size = 0;
    list.capacity = initialCapacity;
    return list;
}

/// \brief 自动扩容函数
/// \param list 顺序表
static void resizeArrayList(ArrayList *list){
    int newCapacity = list->capacity * 2;
    int *newArray = (int *)realloc(list->array, newCapacity * sizeof(int));
    if (newArray){
        list->array = newArray;
        list->capacity = newCapacity;
    } else{
        fprintf(stderr, "顺序表扩容失败：无法为顺序表分配内存！\n");
        exit(EXIT_FAILURE);
    }
}

void addElement(ArrayList *list, int element){
    if (list->size == list->capacity){
        resizeArrayList(list);
    }
    list->array[list->size++] = element;
}

void removeElement(ArrayList *list, int index){
    if (index < 0 || index >= list->size){
        fprintf(stderr, "数组索引越界！\n");
        exit(EXIT_FAILURE);
    }
    for (int i = index; i < list->size - 1; i++){
        list->array[i] = list->array[i + 1];
    }
    list->size--;
}

void setElement(ArrayList *list, int index, int newValue){
    if (index < 0 || index >= list->size){
        fprintf(stderr, "数组索引越界！\n");
        exit(EXIT_FAILURE);
    }
    list->array[index] = newValue;
}

int getElement(ArrayList *list, int index){
    if (index < 0 || index >= list->size){
        fprintf(stderr, "数组索引越界！\n");
        exit(EXIT_FAILURE);
    }
    return list->array[index];
}

void destroyArrayList(ArrayList *list){
    free(list->array);
    list->array = NULL;
    list->size = 0;
    list->capacity = 0;
}